<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>拷贝</title>
</head>
<body>
  <script>
    var a = 123;
    var obj = {};
    
    // 赋值
    var person = {
      name:'爱就一个字',
      hobby:['学习',['看电影','购物'],'锻炼'],
      date:new RegExp('\\w+'),
      function(){}
    }

    /* var person1 = person;
    person1.name = '王晓星'
    person1.hobby[0] = '玩游戏';

    console.log(person)
    console.log(person1); */

    // 浅拷贝
    function shallowCopy(obj){
      var target = {}
      for(var i in obj){
        if(obj.hasOwnProperty(i)){
          target[i] = obj[i]
        }
      }
      return target
    }
    /* var person1 = shallowCopy(person)
    person1.name = '王晓星'
    person1.hobby[0] = '玩游戏';
    console.log(person)
    console.log(person1); */

    // 深拷贝
    function deepClone(obj){
      var cloneObj = new obj.constructor()
      if(obj === null) return obj;
      if(obj instanceof Date) return new Date(obj);
      if(obj instanceof RegExp) return new RegExp(obj);
      if(typeof obj !=='object') return obj;
      for(var i in obj){
        if(obj.hasOwnProperty(i)){
          cloneObj[i] = deepClone(obj[i])
        }
      }
      return cloneObj
    }
    // var person1 = deepClone(person)
    var person1 = JSON.parse(JSON.stringify(person))
    person1.name = '王晓星'
    person1.hobby[0] = '玩游戏';
    console.log(person)
    console.log(person1);


  </script>
</body>
</html>